#ifndef VIDEOWIDGET_H
#define VIDEOWIDGET_H

#include <QWidget>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>

extern "C" {
    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libswscale/swscale.h>
    #include <libavutil/imgutils.h>
}

class VideoDecoderThread : public QThread {
    Q_OBJECT
public:
    VideoDecoderThread(const char* url, AVFrame* frame, QMutex* mutex, QWaitCondition* condition);
    ~VideoDecoderThread();

private:
    const char* url;
    AVFrame* frame;
    QMutex* mutex;
    QWaitCondition* condition;
    AVFormatContext* formatContext = nullptr;
    AVCodecContext* codecContext = nullptr;
    SwsContext* swsContext = nullptr;
    VideoWidget* videoWidget;
    
    void run(void);
};

class VideoWidget : public QWidget {
    Q_OBJECT
public:
    explicit VideoWidget(QWidget *parent = nullptr);
    ~VideoWidget();
protected:
    void paintEvent(QPaintEvent *event) override;
private:
    QThread decoderThread;
    VideoDecoderThread* videoDecoder;
    QMutex mutex;
    QWaitCondition condition;
    AVFrame* frame;
    QImage image;

    void setImage(const QImage &newImage);
};

#endif